import { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
import { from, finalize } from "rxjs";
import { getQuestionService } from "../service/question";
import { message } from "antd";
import { useRequest } from "ahooks";
import { useDispatch } from "react-redux";
import { resetComponents } from "../store/componentsReducer";

function useLoadingQuestionData() {
  const { id = "" } = useParams();
  const dispatch = useDispatch();
  const { data, loading, error, run } = useRequest(
    async (id) => {
      if (!id) throw new Error("没有问卷id");
      const data = await getQuestionService(id);
      return data;
    },
    {
      manual: true,
    }
  );
  useEffect(() => {
    if (!data) return;
    const { title = "", componentList = [] } = data;
    console.log(componentList);
    let selectedId = "";
    if (componentList.length > 0) {
      selectedId = componentList[0].fe_id;
    }
    dispatch(resetComponents({ componentList, selectedId }));
  }, [data]);
  useEffect(() => {
    run(id);
  }, [id]);
  return { loading, error };
  //   const [loading, setLoading] = useState(true);
  //   const [questionData, setQuestionData] = useState({});
  //   useEffect(() => {
  //     from(getQuestionService(id))
  //       .pipe(
  //         finalize(() => {
  //           setLoading(false);
  //         })
  //       )
  //       .subscribe({
  //         next: (res) => {
  //           console.log(res);
  //           setQuestionData(res);
  //         },
  //         error: (error) => {
  //           message.error(JSON.stringify(error));
  //         },
  //       });
  //   }, []);
  // async function load() {
  //   const data = await getQuestionService(id);
  //   return data;
  // }
  // const { loading, data, error } = useRequest(load);
  // return { loading, data, error };
}
export default useLoadingQuestionData;
